package org.study.mybatis.generator.plugins;

import org.mybatis.generator.api.*;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.*;

import java.util.List;

/**
 * 自定义插件：在Mapper中增加一个批量修改(批量逻辑删除)的方法
 * 参考 https://blog.csdn.net/weixin_34259159/article/details/92042225
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2023年12月10日
 */
public class BatchUpdatePlugin extends PluginAdapter {
    private static final String METHOD_NAME = "logicDeleteByIds";

    @Override
    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public boolean clientGenerated(Interface interfaze, IntrospectedTable introspectedTable) {
        // 导入所需类
        interfaze.addImportedType(new FullyQualifiedJavaType("java.util.Collection"));
        interfaze.addImportedType(new FullyQualifiedJavaType("org.apache.ibatis.annotations.Param"));
        // 获取主键列的Java类型(不支持联合主键)
        IntrospectedColumn introspectedColumn = introspectedTable.getPrimaryKeyColumns().get(0);
        FullyQualifiedJavaType fullyQualifiedJavaType = introspectedColumn.getFullyQualifiedJavaType();
        // 增加方法
        Method method = new Method(METHOD_NAME);
        method.setVisibility(JavaVisibility.DEFAULT);
        method.setAbstract(true);
        method.setReturnType(FullyQualifiedJavaType.getIntInstance());
        method.addParameter(new Parameter(FullyQualifiedJavaType.getIntInstance(), "deleteFlag", "@Param(\"deleteFlag\")"));
        method.addParameter(new Parameter(new FullyQualifiedJavaType("Collection<" + fullyQualifiedJavaType + ">"), "list", "@Param(\"list\")"));
        context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable);
        interfaze.addMethod(method);
        return true;
    }

    @Override
    public boolean sqlMapDocumentGenerated(Document document, IntrospectedTable introspectedTable) {
        // 数据库表名
        String tableName = introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime();
        XmlElement parentElement = document.getRootElement();
        // 构建xml节点
        XmlElement deleteLogicByIdsElement = new XmlElement("update");
        deleteLogicByIdsElement.addAttribute(new Attribute("id", METHOD_NAME));
        deleteLogicByIdsElement.addElement(new TextElement("update " + tableName +
                " set deleteFlag = #{deleteFlag}" +
                " where id in" +
                " <foreach item=\"item\" index=\"index\" collection=\"list\" open=\"(\" separator=\",\" close=\")\">" +
                " #{item}" +
                " </foreach>"));
        parentElement.addElement(deleteLogicByIdsElement);
        return true;
    }
}
